package 反射;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author alicat.xu
 * @Date 2021/10/19 9:48 上午
 */
public class ReflectionTest {

    @Test
    public void test1() throws Exception{

        Class clazz = Person.class;
        //通过反射，创建Person类的对象
        Constructor cus = clazz.getConstructor(String.class,int.class);
        Person o = (Person) cus.newInstance("Tom", 12);
        System.out.println(o);

        //通过反射，调用对象指定的属性、方法
        Field age = clazz.getDeclaredField("age");
        age.set(o,10);
        System.out.println(o);

        Method show = clazz.getDeclaredMethod("show");
        show.invoke(o);

        //通过反射调用私有的方法、属性、构造器
        Method show1 = clazz.getDeclaredMethod("show1", String.class);
        show1.setAccessible(true);
        show1.invoke(o,"abc");

        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(o,"ssss");

        System.out.println(o);

    }

    //获取Class实例的方式
    @Test
    public void test2() throws ClassNotFoundException {
        //方式一： 调用运行时类的属性  .class
        Class<Person> clazz1 = Person.class;
        System.out.println(clazz1);

        //方式二：通过运行时类的对象，调用getClass()
        Person person = new Person();
        Class<? extends Person> clazz2 = person.getClass();
        System.out.println(clazz2);


        //方式三：调用Class的静态方法： forName(String classPath)
        Class<?> clazz3 = Class.forName("反射.Person");
        System.out.println(clazz3);

        //方式四：使用类的加载器：ClassLoader
        ClassLoader loader = ReflectionTest.class.getClassLoader();
        Class<?> clazz4 = loader.loadClass("反射.Person");
        System.out.println(clazz4);
    }


    @Test
    public void test3() throws Exception {
        Class<?> clazz = Class.forName("反射.Person");
        Object o = clazz.newInstance();
        Field name = clazz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(o,"abc");
        System.out.println(o);
    }
}
